import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import { Form, Input, Toast } from "antd-mobile";
import NavBarAgain from "../components/NavBarAgain";
import api from "../api";
import "./Login.less";
import ButtonAgain from "../components/ButtonAgain";
import _ from "../assets/utils";
import action from "../store/action";

// 自定义表单校验规则
const validate = {
  phone(_, value) {
    value = value.trim();
    let reg = /^(?:(?:\+|00)86)?1\d{10}$/;
    if (value.length === 0) return Promise.reject(new Error("请填写手机号"));
    if (!reg.test(value)) return Promise.reject(new Error("手机号格式有误"));
    return Promise.resolve();
  },
  code(_, value) {
    value = value.trim();
    let reg = /^\d{6}$/;
    if (value.length === 0) return Promise.reject(new Error("请填写验证码"));
    if (!reg.test(value)) return Promise.reject(new Error("验证码格式有误"));
    return Promise.resolve();
  },
};

export default connect(
  null,
  action.base
)(function Login(props) {
  let { queryUserInfoAsync, navigate, usp } = props;
  const [formIns] = Form.useForm();
  let [disabled, setDisabled] = useState(false);
  let [sendText, setSendText] = useState("发送验证码");

  const submit = async () => {
    try {
      await formIns.validateFields();
      let { phone, code } = formIns.getFieldValue();
      let { code: codeHttp, token } = await api.login(phone, code);
      if (+codeHttp !== 0) {
        Toast.show({
          icon: "fail",
          content: "登陆失败",
        });
        formIns.resetFields(["code"]);
        return;
      }
      // 登陆成功： 存储Token,存储登陆者信息到redux、提示跳转
      _.storage.set("tk", token);
      // 同步redux 信息
      await queryUserInfoAsync();
      Toast.show({
        icon: "success",
        content: "登陆/注册成功",
      });
      let to = usp.get("to");
      to ? navigate(to, { replace: true }) : navigate(-1);
    } catch (_) {}
  };

  let timer = null;
  let num = 31;
  const countdown = () => {
    if (num === 0) {
      clearInterval(timer);
      timer = null;
      setSendText(`发送验证码`);
      setDisabled(false);
      return;
    }
    num--;
    setSendText(`${num}秒后重发`);
  };
  const send = async () => {
    try {
      await formIns.validateFields(["phone"]);
      let phone = formIns.getFieldValue("phone");
      let { code } = await api.sendPhoneCode(phone);
      if (+code !== 0) {
        Toast.show({
          icon: "fail",
          content: "发送失败",
        });
        return;
      }
      // 发送成功
      setDisabled(true);
      countdown();
      if (!timer) timer = setInterval(countdown, 1000);
    } catch (_) {}
  };

  useEffect(() => {
    return () => {
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
    };
  }, []);
  return (
    <div className="login-box">
      <NavBarAgain title="登陆/注册" />
      <Form
        layout="horizontal"
        mode="card"
        form={formIns}
        initialValues={{ phone: "", code: "" }}
        footer={
          <ButtonAgain color="primary" onClick={submit}>
            登陆
          </ButtonAgain>
        }
      >
        <Form.Item
          name="phone"
          label="手机号"
          rules={[{ validator: validate.phone }]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item
          name="code"
          label="验证码"
          rules={[{ validator: validate.code }]}
          extra={
            <ButtonAgain
              size="small"
              color="primary"
              disabled={disabled}
              onClick={send}
            >
              {sendText}
            </ButtonAgain>
          }
        >
          <Input placeholder="请输入验证码" />
        </Form.Item>
      </Form>
    </div>
  );
});
